﻿using System.Diagnostics.CodeAnalysis;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FileCommon.Extensions;

public static class StringExtensions
{
    public static byte[] GetBytes(this string str)
    {
        return str.GetBytes(Encoding.UTF8);
    }


    public static byte[] GetBytes([NotNull] this string str, [NotNull] Encoding encoding)
    {
        return encoding.GetBytes(str);
    }
    
    public static bool IsValidJson(this string text)
    {
        text = text.Trim();
        if ((text.StartsWith("{") && text.EndsWith("}")) || //For object
            (text.StartsWith("[") && text.EndsWith("]"))) //For array
        {
            try
            {
                var obj = JToken.Parse(text);
                return true;
            }
            catch (JsonReaderException jex)
            {
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
}